<template>
  <div class="articleDetails">
    <NavBar />
    <div class="container" v-if="data">
      <div class="guid">
        <router-link to="/">首页</router-link>
        <i>></i>
        <router-link :to="'/plan/'+data.plan.planId">计划</router-link>
        <i>></i>
        <span>正文</span>
      </div>
      <div class="con-lf w73">
        <div class="con w78 fr">
          <div class="txt-con item">
            <div class="head">
              <h1 class="ftz20">{{data.article.title}}</h1>
              <p>
                <span>{{data.article.createTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}')}}</span>
                <span class="mtl3">分类：{{data.author.field}}</span>
                <span class="fr">
                  <img src="../../assets/res/img/icon_label.png">
                  <template v-if="data.article.keyword">
                    <template v-for="(item,index) in data.article.keyword.split(',')">
                      <i v-if="index > 0" :key="'a' + item"> /</i>
                      <span :key="'a-' + item">{{item}}</span>
                    </template>
                  </template>
                </span>
              </p>
            </div>
            <div class="text">
              <div class="abstr">
                <div class="title ftz16">摘要</div>
                <div class="txt">{{data.article.summary}}</div>
              </div>
              <!-- 付费 -->
              <template v-if="data.article.freeFlag===0">
                <!-- 作者本人 -->
                <template v-if="data.plan.userId === userId">
                  <div class="text-con" id="textCon">
                    <div v-html="data.article.details"></div>
                  </div>
                </template>
                <!-- 别人 -->
                <template v-else>
                  <!-- 未购买 -->
                  <template v-if="!data.plan.paid">
                    <div class="text-con" id="textCon">
                      <div class="nopay">
                        <p>这里只是提示内容，详细精彩内容，购买后可阅读全文。这里只是提示内容，详细精彩内容，购买后可阅读全文。 这里只是提示内容，详细精彩内容，购买后可阅读全文。这里只是提示内容，详细精彩内容，购买后可阅读全文。
                        </p>
                        <p>这里只是提示内容，详细精彩内容，购买后可阅读全文。这里只是提示内容，详细精彩内容，购买后可阅读全文。
                          <p>这里只是提示内容，详细精彩内容，购买后可阅读全文。这里只是提示内容，详细精彩内容，购买后可阅读全文。这里只是提示内容，详细精彩内容，购买后可阅读全文。</p>
                          <p>这里只是提示内容，详细精彩内容，购买后可阅读全文。这里只是提示内容，详细精彩内容，购买后可阅读全文。这里只是提示内容，详细精彩内容，购买后可阅读全文。</p>
                          <p>这里只是提示内容，详细精彩内容，购买后可阅读全文。这里只是提示内容，详细精彩内容，购买后可阅读全文。</p>
                          <p>这里只是提示内容，详细精彩内容，购买后可阅读全文。这里只是提示内容，详细精彩内容，购买后可阅读全文。这里只是提示内容，详细精彩内容，购买后可阅读全文。 这里只是提示内容，详细精彩内容，购买后可阅读全文。这里只是提示内容，详细精彩内容，购买后可阅读全文。这里只是提示内容，详细精彩内容，购买后可阅读全文。
                          </p>
                      </div>
                      <div class="more" id="more">
                        <span class="tips">还有{{data.article.detailsRemainLength}}字精彩内容，购买后可阅读全文<br><img src="../../assets/res/img/icon_down.png"></span>
                      </div>
                    </div>
                    <div class="pay">
                      <a href="javascript:void(0)" @click="navTo()">
                        <button>
                          <span class="icon-coin-white"></span>{{parseFloat(data.plan.price)}}购买</button>
                      </a>
                      <span>已有
                        <i>{{data.article.planSaleNum ? data.article.planSaleNum : 0}}</i>人购买</span>
                    </div>
                  </template>
                  <!-- 已购买 -->
                  <template v-else>
                    <div class="text-con" id="textCon">
                      <div v-html="data.article.details"></div>
                    </div>
                  </template>
                </template>
              </template>
              <!-- 免费 -->
              <template v-else>
                <div class="text-con" id="textCon">
                  <div v-html="data.article.details"></div>
                </div>
              </template>
              <div class="state">
                <i>【免责声明】</i>本页面内容不代表平台观点，仅供您参考与学习观摩，您应自主投资决策，自行承担投资风险与损失！
              </div>
              <div class="reward">
                <span class="ml232">此篇文章很值</span>
                <span class="ml86">赞赏激励一下</span>
                <button id="reward" @click="showReward()">赏</button>
              </div>
              <div class="reward-p">
                <span style="display: none" id="reward_aft">
                  <span class="images"><img src=""></span>
                  <span>等
                    <i>1</i>人已赞赏</span>
                </span>
                <span id="reward_bef">首席赞赏官虚位以待</span>
              </div>
              <div class="text-bot">
                <span class="mr10">阅读（{{data.article.hot}}）</span>
                <a href="javascript:void(0)" class="mr10" :class="{on: data.praised}" @click="star(data)">
                  <img v-if="data.praised" src="../../assets/res/img/icon_hand_on.png">
                  <img v-else src="../../assets/res/img/icon_hand.png"> 赞{{data.article.praise > 0 ? data.article.praise: ''}}</a>
                <span>
                  <a href="javascript:void(0)" id="coll" state='0' @click="collect(data)">
                    <template v-if="!data.favorited">
                      <img src="../../assets/res/img/icon_coll.png">收藏
                    </template>
                    <template v-else>
                      <img src="../../assets/res/img/icon_colled.png">取消收藏
                    </template>
                  </a>
                </span>
                <span class="fr">
                  <a v-if="data.enableReport === true" href="javascript:void(0)" class="mr10" id="report" @click="addAlarm()">举报文章</a>
                  <a v-if="data.enableReport === false" href="javascript:void(0)" class="mr10">已举报</a>
                  来源：中亿理投师
                </span>
              </div>
            </div>

          </div>

          <div class="recomm item">
            <div class="item-h">
              <span class="line"></span>
              <b class="ftz16">相关推荐</b>
            </div>
            <div class="recomm-con">
              <ul>
                <li v-for="(item,index) in data.relationArticleList" :key="index">
                  <router-link :to="'/planarticle/' + item.articleId" class="ftz16">{{item.title}}</router-link>
                </li>
              </ul>
            </div>
          </div>
          <comment :articleId="id" :authorId="authorId" :articleType="2" />
        </div>

        <div class="txt-guid fl">
          <div class="item">
            <a href="javascript: void(0)" class="comm ftz16"><img src="../../assets/res/img/icon_txt.png">
              <span>评论</span>
            </a>
            <p>
              <span>分享到</span>
              <a href="javascript: void(0)"><img src="../../assets/res/img/icon_wechat.png" title="微信"></a>
              <a href="javascript: void(0)"><img src="../../assets/res/img/icon_sina.png" title="微博"></a>
            </p>
          </div>
          <div class="item">
            <span>上一篇</span>
            <i style="display:block;color:#ccc;padding:20px 0;" v-if="!data.previous.planId">没有了</i>
            <router-link style="margin:0;cursor: pointer;" :to="'/planarticle/' + data.previous.articleId" v-else class="title">{{data.previous.title}}</router-link>
          </div>
          <div class="item">
            <span>下一篇</span>
            <i style="display:block;color:#ccc;padding:20px 0;" v-if="!data.next.planId">没有了</i>
            <router-link style="margin:0;cursor: pointer;" v-else class="title" :to="'/planarticle/' + data.next.articleId">{{data.next.title}}</router-link>
          </div>
        </div>
      </div>

      <div class="con-rg w23 fr">
        <div class="person item">
          <div class="head">
            <a href="javascript: void(0)" @click="linkToDashboard(data.opinionLeader.userId)" class="photo"><img :src="data.opinionLeader.headImg"></a>
            <span class="name">
              <a href="javascript: void(0)" @click="linkToDashboard(data.opinionLeader.userId)">
                <b class="ftz16">{{data.opinionLeader.authName}}</b>
              </a>
              <span class="line" v-if="data.opinionLeader.authType === '1'"></span>
              <span v-if="data.opinionLeader.authType === '1'">{{data.opinionLeader.orgName}}</span>
            </span>
            <p class="intro">
              <span id="intro">{{data.opinionLeader.descreption}}</span>
              <!-- <a href="javascript:void(0)">展开↓</a> -->
            </p>
            <div class="label">{{{'1':'理投专家','2':'理投机构'}[data.opinionLeader.authType]}}</div>
            <div class="appr"><img src="../../assets/res/img/icon_appr.png"></div>
          </div>
          <div class="bot">
            <button @click="focus()" :class="{'followed': data.opinionLeader.isMyFocus === '0'}">
              {{data.opinionLeader.isMyFocus === '0'?'已关注':'+关注'}}
            </button>
            <button @click.stop.prevent="showQuestionBox(data.author)" v-if="data.author.answerPay > 0">
              <span class="icon-coin-white"></span>{{parseFloat(data.author.answerPay)}}提问</button>
            <button @click.stop.prevent="showQuestionBox(data.author)" v-else>免费提问</button>
          </div>
        </div>
        <LeftPanelViewpoint :list="viewPointList" :authorId="authorId" />
        <LeftPanelLive :list="liveList" :authorId="authorId" />

        <div class="plan item">
          <div class="item-h">
            <span class="line"></span>
            <b class="ftz16">Ta的计划</b>
            <router-link :to="'/dashboard/plan/' + data.opinionLeader.userId" class="fr">更多></router-link>
          </div>
          <div class="con">
            <div class="head">
              <a href="javascript: void(0)" class="img">
                <img src="../../assets/res/img/financing_master.jpg">
              </a>
              <router-link tag="p" :to="'/plan/' + data.plan.planId">
                <a href="javascript: void(0)" class="ftz16">{{data.plan.name}}</a>
                <i>{{data.plan.statusText}}</i>
              </router-link>
            </div>
            <div class="bot">
              <i>{{data.plan.saleNum ? data.plan.saleNum : 0}}</i>人已订阅
              <template v-if="userId !== data.plan.userId">
                <router-link :to="'/plan/' + data.plan.planId" class="fr" :class="{'gray':data.plan.paid === 1}">
                  <template v-if="data.plan.paid === 1">
                    <span>已订阅</span>
                  </template>
                  <template v-else>
                    <span v-if="data.plan.price>0">
                      <span class="icon-coin"></span>{{parseFloat(data.plan.price)}}订阅
                    </span>
                    <span v-else>
                      免费订阅
                    </span>
                  </template>
                </router-link>
              </template>
            </div>
          </div>
        </div>
      </div>
      <div style="width: 0;height: 0;overflow: hidden;">
        <div id="reportArt">
          <div class="margin-bottom-15">
            <div class='radio'>
              <input v-model="reportClassify" value="1" type='radio' id="classify1" title='广告垃圾信息' name='classify' checked>
              <label for="classify1" style="margin-right: 50px;">广告垃圾信息</label>
              <input v-model="reportClassify" value="2" id="classify2" type='radio' title='抄袭或未授权转载' name='classify'>
              <label for="classify2" style="margin-right: 50px;">抄袭或未授权转载</label>
              <input v-model="reportClassify" value="3" id="classify3" type='radio' title='其他' name='classify'>
              <label for="classify3">其他</label>
            </div>
            <textarea v-model="reportContent" class='text' placeholder='请写下举报的详细情况（选填）'></textarea>
          </div>
          <!-- <form class="layui-form">
            <div class="layui-form-item">
              <textarea class="layui-textarea" placeholder="请写下举报详细内容"></textarea>
            </div>
          </form> -->
        </div>
      </div>
    </div>
    <!-- 提问弹窗 -->
    <transition name="fade">
      <QuestionBox v-show="questionBoxFlag" @closeFn="closeQuestionBox" @submitFn="submitQuestion" :masterInfo="targetMasterInfo" />
    </transition>
    <RewardBox v-if="reward" @close="reward=false" @next="payFunc" />
    <PayType v-if="pay" :payInfo="{money:this.remardMoney, articleId: id}" articleType="plan" @close="pay=false" />
    <Footer />
  </div>
</template>
<script>
import RewardBox from '@/view/articleDetails/reward'
import PayType from '@/view/articleDetails/pay'
import NavBar from '@/components/nav-bar'
import Footer from '@/components/footer'
import Comment from '@/components/comment'
import QuestionBox from '@/components/questionAnswer/question-box'
import LeftPanelViewpoint from '@/components/plan/left-panel-viewpoint'
import LeftPanelLive from '@/components/plan/left-panel-live'
import * as api from '@/service/api'
import { mapState } from 'vuex'
import $ from 'jquery'
export default {
  components: {
    NavBar,
    Footer,
    QuestionBox,
    LeftPanelViewpoint,
    LeftPanelLive,
    RewardBox,
    PayType,
    Comment
  },
  data () {
    return {
      id: this.$route.params.id,
      authorId: '', // 作者id
      data: null,
      reportClassify: '1',
      reportContent: '',
      viewPointList: [],
      liveList: [],
      questionBoxFlag: false, // 是否显示提问框
      // 提问的大咖
      targetMasterInfo: {
        id: '',
        name: '',
        avatar: '',
        comment: '',
        field: '',
        answerCount: '',
        answerPay: ''
      },
      reward: false,
      pay: false
    }
  },
  watch: {
    '$route' (to, val) {
      this.id = this.$route.params.id
      this.getArticleDetail()
      return val
    },
    scroll (val) {
      setTimeout(() => {
        if (val === 'bottom') {
          let height = document.getElementById('app').scrollHeight - 400
          document.documentElement.scrollTop = document.body.scrollTop = height
        }
      }, 1000)
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.getArticleDetail()
      if (window.layer) {
        this.layerLoad = window.layer.load(0, {
          shade: false
        })
      }
    })
  },
  computed: {
    ...mapState({
      userInfo: state => state.me.sysUser || {}
    }),
    userId () {
      return this.$store.state.me.sysUser.userId
    },
    scroll () {
      return this.$route.query.scroll
    }
  },
  methods: {

    linkToDashboard (itemId) {
      if (this.userId === itemId) {
        if (this.userInfo.authType === '0') {
          this.$router.push('/dashboardUser')
        } else {
          this.$router.push('/dashboardAuth')
        }
      } else {
        this.$router.push('/dashboard/live/' + itemId)
      }
    },
    addAlarm () {
      let that = this
      window.layer.open({
        title: '举报文章',
        btn: ['确定', '取消'],
        skin: 'report',
        type: 1,
        btnAlign: 'c',
        content: $('#reportArt'),
        yes: function (index, layero) {
          that.handleReport()
        }
      })
    },
    async handleReport () {
      try {
        if (!this.reportContent.length) {
          window.layer.msg('请输入举报内容！', {
            icon: 2
          })
          return false
        }
        await api.handleReport({
          cause: this.reportClassify,
          detail: this.reportContent,
          articleType: '2',
          articleId: this.data.article.articleId
        })
        if (window.layer) {
          window.layer.closeAll()
        }
        window.layer.msg('操作成功')
      } catch (error) {
        console.log(error)
      }
    },
    navTo () {
      if (!this.userId) {
        window.layui.layer.msg('请登录后再购买！')
        return false
      }
      this.$router.push('/plan/pay/' + this.data.article.planId)
    },
    async focus () {
      if (!this.userId) {
        window.layui.layer.msg('请登录后再关注！')
        return false
      }
      let flag = this.data.opinionLeader.isMyFocus === '0' ? '1' : '0'
      await api.modifyUserFocus({
        focusUserId: this.data.opinionLeader.userId,
        focusStatus: flag
      })
      this.data.opinionLeader.isMyFocus = flag
    },
    async getArticleDetail () {
      try {
        let res
        res = await api.getPlanArticleDetail({ articleId: this.id })
        this.data = res.data.data

        this.authorId = this.data.author.userId // 作者id
        // 他的观点
        this.getViewPointList()
        // 他的直播
        this.getLiveThemeList()
      } catch (error) {
      }
    },
    // 获取他的观点
    getViewPointList () {
      let searchInfo = {
        userId: this.authorId,
        pageSize: 6,
        pageNum: 1
      }
      api.getArticleByStatus(searchInfo).then(res => {
        if (res.status === 200) {
          let tempData = res.data
          if (tempData.data) {
            this.viewPointList = tempData.data.list
          }
        } else {
          this.errorMsg('获取他的直播列表失败')
        }
      })
    },
    // 获取他的直播主题列表
    getLiveThemeList () {
      let searchInfo = {
        userId: this.authorId,
        pageSize: 6,
        pageNum: 1
      }
      api.getMyLive(searchInfo).then(res => {
        if (res.status === 200) {
          let tempData = res.data
          this.liveList = tempData.list
        } else {
          this.errorMsg('获取他的直播列表失败')
        }
      })
    },
    // 显示提问弹窗
    showQuestionBox (item) {
      if (!this.userId) {
        window.layui.layer.msg('请登录后再提问！')
        return false
      }
      if (this.userId === item.userId) {
        window.layui.layer.msg('不能向自己提问！')
        return false
      }
      this.questionBoxFlag = true
      let answerPay = item.answerPay
      if (!answerPay) {
        answerPay = 0
      }
      this.targetMasterInfo = {
        id: item.userId,
        name: item.authName,
        avatar: item.avatar,
        comment: item.comment,
        field: item.field,
        fieldId: item.fieldId,
        answerCount: item.answerCount | 0,
        answerPay: answerPay
      }
    },
    // 关闭提问弹窗
    closeQuestionBox () {
      this.questionBoxFlag = false
    },
    // 提交问题
    submitQuestion () {
      this.questionBoxFlag = false
    },
    // 点赞
    async star (item) {
      if (!this.userId) {
        window.layui.layer.msg('请登录后再点赞！')
        return
      }
      if (item.praised) {
        return
      }
      let res = await api.praisePlanArticle({ articleId: item.article.articleId })
      if (res.data && res.data.code === 200) {
        item.praised = true
        item.article.praise++
      }
    },
    // 收藏
    collect (item) {
      if (!this.userId) {
        window.layui.layer.msg('请登录后再收藏！')
        return
      }
      if (!item.favorited) {
        this.execCollect(true, item) // 收藏
      } else {
        let title = '确认取消收藏该文章吗?'
        this.showConfirmBox(title, () => {
          this.execCollect(false, item) // 取消收藏
        })
      }
    },
    showConfirmBox (title, callback) {
      window.layer.open({
        type: 1,
        offset: 'auto',
        id: 'layerDemo' + 'auto', // 防止重复弹出
        content: '<div style="padding: 20px 100px;">' + title + '</div>',
        btn: '确认',
        btnAlign: 'c',
        shade: 0,
        yes: function () {
          callback()
          if (window.layer) {
            window.layer.closeAll()
          }
        }
      })
    },
    async execCollect (target, item) {
      let res = null
      if (!target) {
        res = await api.unFavoritePlanArticle({ articleId: item.article.articleId })
      } else {
        res = await api.favoritePlanArticle({ articleId: item.article.articleId })
      }
      if (res.data && res.data.code === 200) {
        item.favorited = target
      }
    },
    // 显示打赏框
    showReward (item) {
      if (!this.userId) {
        window.layui.layer.msg('请登录后再打赏！')
        return false
      }
      if (this.userId === this.data.article.userId) {
        window.layui.layer.msg('不能给自己打赏！')
        return false
      }
      this.reward = true
    },
    payFunc (money) {
      this.reward = false
      this.pay = true
      this.remardMoney = money
    }
  }
}
</script>
<style lang="scss">
@import "../../style/res/content";
.articleDetail {
  .layui-layer {
    min-width: 518px;
  }
  .layui-layer-content {
    padding: 20px;
  }
}
</style>
